package com.bkgrands.fpmu.activities;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.tu.loadingdialog.LoadingDialog;
import com.bkgrands.fpmu.R;
import com.bkgrands.fpmu.Retro.APIClient;
import com.bkgrands.fpmu.Retro.APIInterface;
import com.bkgrands.fpmu.classes.SetProgressResponse;
import com.bkgrands.fpmu.classes.StaticFarm;
import com.bkgrands.fpmu.classes.UploadPhotoResponse;
import com.jeevandeshmukh.glidetoastlib.GlideToast;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.DexterError;
import com.karumi.dexter.listener.PermissionRequestErrorListener;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;

import es.dmoral.toasty.Toasty;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class ProgressActivity extends AppCompatActivity {
    Button wait, start, done, cont;
    EditText caption;
    ImageButton capture;
    ImageView shot;
    TextView section_label1;
    APIInterface apiInterface;
    String Choice;
    Bitmap bitmap;
    private Context mContext;
    private int GALLERY = 1, CAMERA = 2;
    private static final String IMAGE_DIRECTORY = "/YourDirectName";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress);
        wait = (Button) findViewById(R.id.waiting);
        start = (Button) findViewById(R.id.notyet);
        done = (Button) findViewById(R.id.done);
        cont = (Button) findViewById(R.id.btncontinue);
        caption = (EditText) findViewById(R.id.input_password);
        capture = (ImageButton) findViewById(R.id.capture);
        shot = (ImageView) findViewById(R.id.shot);
        section_label1 = (TextView) findViewById(R.id.section_label1);

        apiInterface = APIClient.getClient().create(APIInterface.class);

       // bitmap = BitmapFactory.decodeResource(shot.getDrawable());
        Intent startingIntent = getIntent();
        String majorname = startingIntent.getStringExtra("minormajor");
        String status = startingIntent.getStringExtra("progressStatus");
        if (status.equals("pending")){
            wait.setBackgroundColor(Color.YELLOW);
            wait.setTextColor(Color.BLACK);
        }if (status.equals("done")){
            done.setBackgroundColor(Color.GREEN);
            done.setTextColor(Color.BLACK);
        }if (status.equals("not-started")){
            start.setBackgroundColor(Color.RED);
            start.setTextColor(Color.BLACK);
        }
        section_label1.setText(majorname + " Status");
        requestMultiplePermissions();

        start.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    start.setBackgroundColor(Color.RED);
                    Toasty.normal(getApplicationContext(), "Selected :" + String.valueOf(start.getText().toString()), R.drawable.success).show();
                    Choice = String.valueOf(start.getText().toString());
                } else if (event.getAction() == KeyEvent.ACTION_UP) {
                    wait.setTextColor(Color.BLACK);
                    wait.setBackground(getResources().getDrawable(R.drawable.yellow));
                    done.setTextColor(Color.BLACK);
                    done.setBackground(getResources().getDrawable(R.drawable.green));
                }
                return false;
            }
        });

        //Change the button background color from black to red on touch and  red to black on release

        wait.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    wait.setBackgroundColor(Color.YELLOW);
                    Toasty.normal(getApplicationContext(), "Selected :" + String.valueOf(wait.getText().toString()), R.drawable.success).show();
                    Choice = String.valueOf(wait.getText().toString());
                } else if (event.getAction() == KeyEvent.ACTION_UP) {
                    start.setTextColor(Color.BLACK);
                    start.setBackground(getResources().getDrawable(R.drawable.red));
                    done.setTextColor(Color.BLACK);
                    done.setBackground(getResources().getDrawable(R.drawable.green));
                }
                return false;
            }
        });


        done.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    done.setBackgroundColor(Color.GREEN);
                    Toasty.normal(getApplicationContext(), "Selected :" + String.valueOf(done.getText().toString()), R.drawable.success).show();
                    Choice = String.valueOf(done.getText().toString());
                } else if (event.getAction() == KeyEvent.ACTION_UP) {
                    start.setTextColor(Color.BLACK);
                    start.setBackground(getResources().getDrawable(R.drawable.red));
                    wait.setTextColor(Color.BLACK);
                    wait.setBackground(getResources().getDrawable(R.drawable.yellow));
                }
                return false;
            }
        });

        capture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPictureDialog();
            }
        });

        cont.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (!validateData() || !validateData2()) {
//                    return;
//                }
//                    Toasty.success(getApplicationContext(), "Final selection is :" + Choice, Toast.LENGTH_SHORT, true).show();
                  uploadImage2Server();
//                uploadStatus2Server();
            }
        });


    }

    private boolean validateData() {
        boolean valid = true;
        String name = caption.getText().toString();
        if (name == null || name == "" || shot.getDrawable() == null) {
            Toasty.warning(getApplicationContext(), "Please provide a Caption and an Image", Toast.LENGTH_SHORT, true).show();
        }
        return valid;
    }

    private boolean validateData2() {
        boolean valid = true;
        if (Choice == null || Choice == "") {
            Toasty.warning(getApplicationContext(), "Please Select a Status.", Toast.LENGTH_SHORT, true).show();
        }
        return valid;
    }


    private void showPictureDialog() {
        AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
        pictureDialog.setTitle("Select Action");
        String[] pictureDialogItems = {"Select photo from gallery", "Capture photo from camera"};
        pictureDialog.setItems(pictureDialogItems,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                choosePhotoFromGallary();
                                break;
                            case 1:
                                takePhotoFromCamera();
                                break;
                        }
                    }
                });
        pictureDialog.show();
    }

    public void choosePhotoFromGallary() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(galleryIntent, GALLERY);
    }

    private void takePhotoFromCamera() {
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, CAMERA);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == this.RESULT_CANCELED) {
            return;
        }
        if (requestCode == GALLERY) {
            if (data != null) {
                Uri contentURI = data.getData();
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
                    String path = saveImage(bitmap);
                    StaticFarm.currentPhotoToUpload = path;
                    Toasty.success(getApplicationContext(), "Image Saved!"+path, Toast.LENGTH_SHORT, true).show();
                    shot.setImageBitmap(bitmap);

                } catch (IOException e) {
                    e.printStackTrace();
                    Toasty.error(getApplicationContext(), "Error saving Image. ", Toast.LENGTH_SHORT, true).show();
                }
            }

        } else if (requestCode == CAMERA) {
            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            shot.setImageBitmap(thumbnail);
            String path = saveImage(thumbnail);

            StaticFarm.currentPhotoToUpload = path;

            Toasty.success(getApplicationContext(), "Image Saved! "+path, Toast.LENGTH_SHORT, true).show();
        }
    }

    public String saveImage(Bitmap myBitmap) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        File wallpaperDirectory = new File(Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
        if (!wallpaperDirectory.exists()) {  // have the object build the directory structure, if needed.
            wallpaperDirectory.mkdirs();
        }

        try {
            File f = new File(wallpaperDirectory, Calendar.getInstance().getTimeInMillis() + ".jpg");
            f.createNewFile();
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
            MediaScannerConnection.scanFile(this,
                    new String[]{f.getPath()},
                    new String[]{"image/jpeg"}, null);
            fo.close();

            return f.getAbsolutePath();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return "";
    }

    private void requestMultiplePermissions() {
        Dexter.withActivity(this)
                .withPermissions(
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE)
                .withListener(new MultiplePermissionsListener() {
                    @Override
                    public void onPermissionsChecked(MultiplePermissionsReport report) {
                        if (report.areAllPermissionsGranted()) {  // check if all permissions are granted
                            Toasty.success(getApplicationContext(), "All Permissions granted!", Toast.LENGTH_SHORT, true).show();
                        }

                        if (report.isAnyPermissionPermanentlyDenied()) { // check for permanent denial of any permission

                        }
                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(List<com.karumi.dexter.listener.PermissionRequest> permissions, PermissionToken token) {

                    }

                }).
                withErrorListener(new PermissionRequestErrorListener() {
                    @Override
                    public void onError(DexterError error) {
                        Toasty.error(getApplicationContext(), "Error Granting Permission.", Toast.LENGTH_SHORT, true).show();
                    }
                })
                .onSameThread()
                .check();
    }


    private String imagetoString() {
        Bitmap bm=((BitmapDrawable)shot.getDrawable()).getBitmap();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
        byte[] imagByte = byteArrayOutputStream.toByteArray();
        return Base64.encodeToString(imagByte, Base64.DEFAULT);
    }


    private String getRealPathFromURI(Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        CursorLoader loader = new CursorLoader(this, contentUri, proj, null, null, null);
        Cursor cursor = loader.loadInBackground();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String result = cursor.getString(column_index);
        cursor.close();
        return result;
    }


    public void uploadImage2Server() {
        LoadingDialog.Builder builder1 = new LoadingDialog.Builder(ProgressActivity.this)
                .setMessage("Uploading Report...")
                .setCancelable(false);
        final LoadingDialog dialog1 = builder1.create();
        dialog1.show();

        String progress_id = StaticFarm.currentMinorStage.getProgress().getId();
        String projectcaption = caption.getText().toString();

//        String image = imagetoString();

        File file = new File(StaticFarm.currentPhotoToUpload);
        Uri uri = Uri.fromFile(file);

        String fileExtension
                = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
        String mimeType
                = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);

        RequestBody requestFile = RequestBody.create(MediaType.parse(mimeType), file);
        RequestBody captionBody = RequestBody.create(MediaType.parse("text/plain"), projectcaption);
        RequestBody progressIDBody = RequestBody.create(MediaType.parse("text/plain"), progress_id);


        Call<UploadPhotoResponse> call = apiInterface.uploadImage(requestFile, captionBody, progressIDBody);
        call.enqueue(new Callback<UploadPhotoResponse>() {
            @Override
            public void onResponse(Call<UploadPhotoResponse> call, Response<UploadPhotoResponse> response) {
                if (response.isSuccessful()) {
                    UploadPhotoResponse uploadPhotoResponse = response.body();
                    if (uploadPhotoResponse.getStatus().equals("success")) {
                        dialog1.dismiss();
                        finish();
                        StaticFarm.currentphotoResponse = uploadPhotoResponse;
                    } else {
                        new GlideToast.makeToast(ProgressActivity.this, "UpLoad Successful...", GlideToast.LENGTHLONG, GlideToast.FAILTOAST, GlideToast.BOTTOM).show();
                        //error code
                        dialog1.dismiss();
                    }


                } else {
                    new GlideToast.makeToast(ProgressActivity.this, "Response Failed", GlideToast.LENGTHLONG, GlideToast.FAILTOAST, GlideToast.BOTTOM).show();
                    // <<error code
                    dialog1.dismiss();
                }
            }

            @Override
            public void onFailure(Call<UploadPhotoResponse> call, Throwable t) {
                dialog1.dismiss();
                new GlideToast.makeToast(ProgressActivity.this, "Upload Failed", GlideToast.LENGTHLONG, GlideToast.FAILTOAST, GlideToast.BOTTOM).show();
            }
        });

    }

    public void uploadStatus2Server(){
        LoadingDialog.Builder builder1 = new LoadingDialog.Builder(ProgressActivity.this)
                .setMessage("Uploading Status...")
                .setCancelable(false);
        final LoadingDialog dialog1 = builder1.create();
        dialog1.show();

        String stageid= StaticFarm.currentMinorStage.getId();
        String siteid=StaticFarm.currentSite.getId();
        String tempid =StaticFarm.currentSite.getTmplId();
        String hash =StaticFarm.currentMinorStage.getHash();

       Call<SetProgressResponse>call =apiInterface.setProgressStatus(stageid,siteid,tempid,hash,Choice);
       call.enqueue(new Callback<SetProgressResponse>() {
           @Override
           public void onResponse(Call<SetProgressResponse> call, Response<SetProgressResponse> response) {
            if (response.isSuccessful()){
                // get response
                SetProgressResponse setProgressResponse = response.body();
                String xxx = setProgressResponse.toString();

                if(setProgressResponse.getAction().equals("updated")) {
                    dialog1.dismiss();
                    Toasty.success(getApplicationContext(), "Response Successful", Toast.LENGTH_SHORT, true).show();
                    ProgressActivity.this.finish();
                }
            }else {
                dialog1.dismiss();
                Toasty.success(getApplicationContext(), "Response Failed!", Toast.LENGTH_SHORT, true).show();

            }

           }

           @Override
           public void onFailure(Call<SetProgressResponse> call, Throwable t) {
               dialog1.dismiss();
               Toasty.success(getApplicationContext(), "Response Failed!", Toast.LENGTH_SHORT, true).show();
           }
       });

    }

}

